package me.kuye.jkuye.plugin.activerecord;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

import me.kuye.jkuye.log.Logger;

public class SqlReporter implements InvocationHandler {
	private Connection connection;
	private static boolean loggerOn = false;
	private static final Logger logger = Logger.getLogger(SqlReporter.class);

	public SqlReporter(Connection connection) {
		this.connection = connection;
	}

	Connection getConnection() {
		Class clazz = Connection.class;
		return (Connection) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { Connection.class }, this);
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		try {
			if (method.getName().equals("prepareStatement")) {
				String message = "SQL : " + args[0];
				if (loggerOn) {
					logger.info(message);
				} else {
					System.out.println(message);
				}
			}
			return method.invoke(proxy, args);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static void setLogger(boolean loggerOn) {
		SqlReporter.loggerOn = loggerOn;
	}
}
